<template>
  <div class="post-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 文章内容 -->
    <div v-else-if="post" class="post-content">
      <!-- 文章头部 -->
      <div class="post-header">
        <div class="post-meta">
          <div class="author-info">
            <el-avatar :size="48" :src="post.user?.avatarUrl" class="author-avatar">
              {{ post.user?.username?.charAt(0) }}
            </el-avatar>
            <div class="author-details">
              <h3 class="author-name">{{ post.user?.username }}</h3>
              <p class="post-time">{{ formatDate(post.createdAt) }}</p>
            </div>
          </div>
          <div class="post-actions">
            <el-button 
              :type="post.isLiked ? 'primary' : 'default'" 
              @click="toggleLike"
              :loading="likeLoading"
            >
              <el-icon><Star /></el-icon>
              {{ post.isLiked ? '已赞' : '点赞' }} ({{ post.likeCount || 0 }})
            </el-button>
            <el-button 
              :type="post.isFollowed ? 'primary' : 'default'" 
              @click="toggleFollow"
              :loading="followLoading"
            >
              <el-icon><Plus /></el-icon>
              {{ post.isFollowed ? '已关注' : '关注' }}
            </el-button>
            <el-button @click="sharePost">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
          </div>
        </div>
        
        <h1 class="post-title">{{ post.title }}</h1>
        
        <div class="post-tags">
          <el-tag 
            v-for="tag in post.tags" 
            :key="tag" 
            type="info" 
            size="large"
            class="post-tag"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>

      <!-- 文章统计 -->
      <div class="post-stats">
        <div class="stat-item">
          <el-icon><View /></el-icon>
          <span>{{ post.viewCount || 0 }} 浏览</span>
        </div>
        <div class="stat-item">
          <el-icon><ChatDotSquare /></el-icon>
          <span>{{ post.replyCount || 0 }} 回复</span>
        </div>
        <div class="stat-item">
          <el-icon><Star /></el-icon>
          <span>{{ post.likeCount || 0 }} 点赞</span>
        </div>
        <div class="stat-item">
          <el-icon><Collection /></el-icon>
          <span>{{ post.collectCount || 0 }} 收藏</span>
        </div>
      </div>

      <!-- 文章正文 -->
      <div class="post-body">
        <div class="post-content-text" v-html="formatContent(post.content)"></div>
      </div>

      <!-- 文章底部操作 -->
      <div class="post-footer">
        <div class="action-buttons">
          <el-button 
            type="primary" 
            @click="toggleLike"
            :loading="likeLoading"
            size="large"
          >
            <el-icon><Star /></el-icon>
            {{ post.isLiked ? '已赞' : '点赞' }} ({{ post.likeCount || 0 }})
          </el-button>
          <el-button 
            @click="toggleCollect"
            :loading="collectLoading"
            size="large"
          >
            <el-icon><Collection /></el-icon>
            {{ post.isCollected ? '已收藏' : '收藏' }} ({{ post.collectCount || 0 }})
          </el-button>
          <el-button @click="sharePost" size="large">
            <el-icon><Share /></el-icon>
            分享
          </el-button>
        </div>
      </div>
    </div>

    <!-- 评论区 -->
    <div class="comments-section">
      <div class="comments-header">
        <h3>评论 ({{ comments.length }})</h3>
        <el-button type="primary" @click="showReplyForm = !showReplyForm">
          <el-icon><Edit /></el-icon>
          写评论
        </el-button>
      </div>

      <!-- 回复表单 -->
      <div v-if="showReplyForm" class="reply-form">
        <el-input
          v-model="replyContent"
          type="textarea"
          :rows="4"
          placeholder="写下你的评论..."
          maxlength="500"
          show-word-limit
        />
        <div class="reply-actions">
          <el-button @click="cancelReply">取消</el-button>
          <el-button type="primary" @click="submitReply" :loading="replyLoading">
            发表评论
          </el-button>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list">
        <div 
          v-for="comment in comments" 
          :key="comment.id" 
          class="comment-item"
        >
          <div class="comment-header">
            <el-avatar :size="32" :src="comment.user?.avatarUrl">
              {{ comment.user?.username?.charAt(0) }}
            </el-avatar>
            <div class="comment-meta">
              <span class="comment-author">{{ comment.user?.username }}</span>
              <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
            </div>
            <div class="comment-actions">
              <el-button size="small" text @click="toggleCommentLike(comment)">
                <el-icon><Star /></el-icon>
                {{ comment.likeCount || 0 }}
              </el-button>
              <el-button size="small" text @click="replyToComment(comment)">
                回复
              </el-button>
            </div>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          
          <!-- 子评论 -->
          <div v-if="comment.replies && comment.replies.length > 0" class="comment-replies">
            <div 
              v-for="reply in comment.replies" 
              :key="reply.id" 
              class="reply-item"
            >
              <el-avatar :size="24" :src="reply.user?.avatarUrl">
                {{ reply.user?.username?.charAt(0) }}
              </el-avatar>
              <div class="reply-content">
                <span class="reply-author">{{ reply.user?.username }}</span>
                <span class="reply-text">{{ reply.content }}</span>
                <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="comments-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalComments"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 相关文章推荐 -->
    <div class="related-posts">
      <h3>相关文章推荐</h3>
      <div class="related-posts-list">
        <div 
          v-for="relatedPost in relatedPosts" 
          :key="relatedPost.id" 
          class="related-post-item"
          @click="navigateToPost(relatedPost.id)"
        >
          <h4>{{ relatedPost.title }}</h4>
          <p>{{ relatedPost.summary }}</p>
          <div class="related-post-meta">
            <span>{{ relatedPost.user?.username }}</span>
            <span>{{ formatDate(relatedPost.createdAt) }}</span>
            <span>{{ relatedPost.viewCount }} 浏览</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  Star, View, ChatDotSquare, Collection, Share, Edit, Plus
} from '@element-plus/icons-vue';
import { getPostDetail, getPostComments } from '@/api/forum';
import { addBrowseHistory } from '@/api/history';
import { addCollection, removeCollection } from '@/api/collection';

const route = useRoute();
const router = useRouter();

// 响应式数据
const loading = ref(true);
const post = ref<any>(null);
const comments = ref<any[]>([]);
const relatedPosts = ref<any[]>([]);
const showReplyForm = ref(false);
const replyContent = ref('');
const replyLoading = ref(false);
const likeLoading = ref(false);
const followLoading = ref(false);
const collectLoading = ref(false);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalComments = ref(0);

// 模拟数据
const mockPost = {
  id: 1,
  title: '2024年公务员考试行测备考经验分享',
  content: `
    <h2>前言</h2>
    <p>作为一名刚刚通过2024年公务员考试行测的考生，我想分享一下自己的备考经验，希望能对正在备考的同学们有所帮助。</p>
    
    <h2>备考时间安排</h2>
    <p>我建议至少提前6个月开始准备，每天保证3-4小时的学习时间。前3个月主要打基础，后3个月进行强化训练和模拟考试。</p>
    
    <h2>各模块备考策略</h2>
    <h3>1. 言语理解与表达</h3>
    <p>这个模块主要考察语言运用能力，需要大量练习。我建议：</p>
    <ul>
      <li>每天做50道题目，保持语感</li>
      <li>重点掌握成语、词语搭配</li>
      <li>多做阅读理解，提高阅读速度</li>
    </ul>
    
    <h3>2. 数量关系</h3>
    <p>数学基础好的同学可以重点攻克，基础薄弱的建议适当放弃部分难题：</p>
    <ul>
      <li>掌握基本公式和解题技巧</li>
      <li>重点练习常考题型</li>
      <li>合理分配时间，不要在一道题上花费太多时间</li>
    </ul>
    
    <h3>3. 判断推理</h3>
    <p>这个模块相对容易提分，建议重点突破：</p>
    <ul>
      <li>图形推理要多做练习，培养空间想象能力</li>
      <li>逻辑判断要掌握基本逻辑关系</li>
      <li>定义判断要仔细阅读，抓住关键词</li>
    </ul>
    
    <h3>4. 资料分析</h3>
    <p>这是最容易得满分的模块，一定要重点练习：</p>
    <ul>
      <li>掌握基本计算公式</li>
      <li>提高计算速度和准确性</li>
      <li>学会快速定位关键信息</li>
    </ul>
    
    <h2>模拟考试</h2>
    <p>最后一个月要严格按照考试时间进行模拟考试，培养时间观念和考试状态。建议每周至少进行2-3次完整的模拟考试。</p>
    
    <h2>心态调整</h2>
    <p>备考过程中要保持良好的心态，不要因为一时的挫折而放弃。相信只要方法正确，坚持努力，一定能够取得好成绩。</p>
    
    <p>最后，祝愿所有备考的同学都能顺利通过考试，实现自己的公务员梦想！</p>
  `,
  user: {
    id: 1,
    username: '公考达人',
    avatarUrl: ''
  },
  category: {
    id: 1,
    name: '行测'
  },
  tags: ['行测', '备考经验', '2024年', '公务员考试'],
  viewCount: 1256,
  replyCount: 89,
  likeCount: 156,
  collectCount: 67,
  isLiked: false,
  isFollowed: false,
  isCollected: false,
  createdAt: '2024-01-15T10:30:00Z'
};

const mockComments = [
  {
    id: 1,
    content: '感谢分享！这些经验对我很有帮助，特别是资料分析的部分。',
    user: {
      id: 2,
      username: '备考小白',
      avatarUrl: ''
    },
    likeCount: 12,
    createdAt: '2024-01-15T14:20:00Z',
    replies: [
      {
        id: 11,
        content: '同感！资料分析确实是最容易提分的模块。',
        user: {
          id: 3,
          username: '行测新手',
          avatarUrl: ''
        },
        createdAt: '2024-01-15T15:30:00Z'
      }
    ]
  },
  {
    id: 2,
    content: '请问楼主，数量关系部分有什么推荐的教材吗？',
    user: {
      id: 4,
      username: '数学困难户',
      avatarUrl: ''
    },
    likeCount: 8,
    createdAt: '2024-01-15T16:45:00Z',
    replies: []
  },
  {
    id: 3,
    content: '模拟考试真的很重要，我就是在最后一个月通过大量模拟提高了成绩。',
    user: {
      id: 5,
      username: '上岸成功',
      avatarUrl: ''
    },
    likeCount: 15,
    createdAt: '2024-01-15T18:10:00Z',
    replies: []
  }
];

const mockRelatedPosts = [
  {
    id: 2,
    title: '申论写作技巧：如何快速提高申论分数',
    summary: '分享申论写作的核心技巧和提分方法...',
    user: { username: '申论专家' },
    viewCount: 892,
    createdAt: '2024-01-14T09:15:00Z'
  },
  {
    id: 3,
    title: '面试准备：公务员面试常见问题及回答技巧',
    summary: '详细介绍公务员面试的各个环节和注意事项...',
    user: { username: '面试导师' },
    viewCount: 654,
    createdAt: '2024-01-13T16:20:00Z'
  },
  {
    id: 4,
    title: '2024年公务员考试时间安排和报名流程',
    summary: '最新的考试时间安排和详细的报名流程指导...',
    user: { username: '考试助手' },
    viewCount: 1234,
    createdAt: '2024-01-12T11:30:00Z'
  }
];

// 加载文章数据
const loadPost = async () => {
  loading.value = true;
  try {
    
    // 从路由参数获取文章ID
    const postId = route.params.id;
    console.log('加载帖子详情，ID:', postId);
    
    // 调用API获取帖子详情
    const postData = await getPostDetail(Number(postId));
    console.log('API返回的帖子数据:', postData);
    
    post.value = postData;
    
    // 加载评论数据
    const commentsData = await getPostComments(Number(postId), {
      page: currentPage.value,
      pageSize: pageSize.value
    });
    
    comments.value = commentsData.items || [];
    totalComments.value = commentsData.total || 0;
    
    // 相关文章推荐（暂时使用模拟数据）
    relatedPosts.value = mockRelatedPosts;
    
    // 记录浏览历史
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1';
    console.log('开始记录浏览历史，用户ID:', userId, '帖子数据:', post.value);
    if (userId && post.value) {
      // 创建浏览历史数据
      console.log('创建浏览历史数据（API数据），post.value:', post.value);
      console.log('post.value.title:', post.value.title);
      const historyData = {
        id: Date.now(),
        userId: Number(userId),
        contentType: 'FORUM',
        contentId: Number(postId),
        contentTitle: post.value.title || '未知标题',
        contentDescription: post.value.content?.substring(0, 100) || '',
        contentUrl: `/forum/post/${postId}`,
        browseTime: new Date().toISOString(),
        createdAt: new Date().toISOString()
      };
      
      try {
        // 尝试调用API
        await addBrowseHistory({
          userId: Number(userId),
          contentType: 'FORUM',
          contentId: Number(postId),
          contentTitle: post.value.title,
          contentDescription: post.value.content?.substring(0, 100),
          contentUrl: `/forum/post/${postId}`
        });
        console.log('API浏览历史记录成功');
      } catch (historyError) {
        console.error('API记录浏览历史失败，使用本地存储:', historyError);
      }
      
      // 无论API是否成功，都保存到本地存储
      const historyKey = `browse_history_${userId}`;
      const existingHistory = JSON.parse(localStorage.getItem(historyKey) || '[]');
      
      // 检查是否已存在相同的浏览记录
      const existingIndex = existingHistory.findIndex((item: any) => 
        item.contentType === 'FORUM' && item.contentId === Number(postId)
      );
      
      if (existingIndex !== -1) {
        // 如果已存在，更新浏览时间
        existingHistory[existingIndex].browseTime = new Date().toISOString();
      } else {
        // 如果不存在，添加新记录
        existingHistory.unshift(historyData);
      }
      
      // 只保留最近100条记录
      if (existingHistory.length > 100) {
        existingHistory.splice(100);
      }
      
      localStorage.setItem(historyKey, JSON.stringify(existingHistory));
      console.log('浏览历史已保存到本地存储，键名:', historyKey, '数据量:', existingHistory.length);
    } else {
      console.log('浏览历史记录条件不满足，用户ID:', userId, '帖子数据存在:', !!post.value);
    }
    
    console.log('帖子加载完成:', post.value);
    
  } catch (error) {
    console.error('加载文章失败:', error);
    ElMessage.error('加载文章失败，请稍后重试');
    
    // 如果API失败，使用模拟数据作为回退
    const postId = route.params.id;
    post.value = { ...mockPost, id: postId };
    comments.value = mockComments;
    
    // 即使使用模拟数据，也要记录浏览历史
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id');
    if (userId && post.value) {
      // 创建浏览历史数据
      console.log('创建浏览历史数据（模拟数据），post.value:', post.value);
      console.log('post.value.title:', post.value.title);
      const historyData = {
        id: Date.now(),
        userId: Number(userId),
        contentType: 'FORUM',
        contentId: Number(postId),
        contentTitle: post.value.title || '未知标题',
        contentDescription: post.value.content?.substring(0, 100) || '',
        contentUrl: `/forum/post/${postId}`,
        browseTime: new Date().toISOString(),
        createdAt: new Date().toISOString()
      };
      
      // 保存到本地存储
      const historyKey = `browse_history_${userId}`;
      const existingHistory = JSON.parse(localStorage.getItem(historyKey) || '[]');
      
      // 检查是否已存在相同的浏览记录
      const existingIndex = existingHistory.findIndex((item: any) => 
        item.contentType === 'FORUM' && item.contentId === Number(postId)
      );
      
      if (existingIndex !== -1) {
        // 如果已存在，更新浏览时间
        existingHistory[existingIndex].browseTime = new Date().toISOString();
      } else {
        // 如果不存在，添加新记录
        existingHistory.unshift(historyData);
      }
      
      // 只保留最近100条记录
      if (existingHistory.length > 100) {
        existingHistory.splice(100);
      }
      
      localStorage.setItem(historyKey, JSON.stringify(existingHistory));
      console.log('浏览历史已保存到本地存储（模拟数据）');
      console.log('保存的数据:', existingHistory);
      console.log('最新记录的标题:', existingHistory[0]?.contentTitle);
    }
    relatedPosts.value = mockRelatedPosts;
    totalComments.value = comments.value.length;
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 格式化内容（简单的HTML渲染）
const formatContent = (content: string) => {
  return content.replace(/\n/g, '<br>');
};

// 点赞功能
const toggleLike = async () => {
  if (!post.value) return;
  
  likeLoading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    post.value.isLiked = !post.value.isLiked;
    if (post.value.isLiked) {
      post.value.likeCount = (post.value.likeCount || 0) + 1;
      ElMessage.success('点赞成功');
    } else {
      post.value.likeCount = Math.max(0, (post.value.likeCount || 0) - 1);
      ElMessage.info('取消点赞');
    }
  } catch (error) {
    ElMessage.error('操作失败');
  } finally {
    likeLoading.value = false;
  }
};

// 关注功能
const toggleFollow = async () => {
  if (!post.value) return;
  
  followLoading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    post.value.isFollowed = !post.value.isFollowed;
    if (post.value.isFollowed) {
      ElMessage.success('关注成功');
    } else {
      ElMessage.info('取消关注');
    }
  } catch (error) {
    ElMessage.error('操作失败');
  } finally {
    followLoading.value = false;
  }
};

// 收藏功能
const toggleCollect = async () => {
  if (!post.value) return;
  
  collectLoading.value = true;
  try {
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1';
    
    if (post.value.isCollected) {
      // 取消收藏
      try {
        await removeCollection(Number(userId), 'FORUM', Number(post.value.id));
        post.value.isCollected = false;
        post.value.collectCount = Math.max(0, (post.value.collectCount || 0) - 1);
        ElMessage.success('取消收藏成功');
      } catch (error) {
        console.error('取消收藏失败:', error);
        ElMessage.error('取消收藏失败');
      }
    } else {
      // 添加收藏
      try {
        await addCollection({
          userId: Number(userId),
          contentType: 'FORUM',
          contentId: Number(post.value.id),
          contentTitle: post.value.title,
          contentDescription: post.value.content?.substring(0, 100),
          contentUrl: `/forum/post/${post.value.id}`
        });
        post.value.isCollected = true;
        post.value.collectCount = (post.value.collectCount || 0) + 1;
        ElMessage.success('收藏成功');
      } catch (error) {
        console.error('收藏失败:', error);
        // 如果API失败，保存到本地存储
        const collectionKey = `collections_${userId}`;
        const existingCollections = JSON.parse(localStorage.getItem(collectionKey) || '[]');
        
        // 检查是否已存在相同的收藏
        const existingIndex = existingCollections.findIndex((item: any) => 
          item.contentType === 'FORUM' && item.contentId === Number(post.value.id)
        );
        
        if (existingIndex === -1) {
          const newCollectionItem = {
            id: Date.now(),
            userId: Number(userId),
            contentType: 'FORUM',
            contentId: Number(post.value.id),
            contentTitle: post.value.title,
            contentDescription: post.value.content?.substring(0, 100),
            contentUrl: `/forum/post/${post.value.id}`,
            collectTime: new Date().toISOString(),
            createdAt: new Date().toISOString()
          };
          existingCollections.unshift(newCollectionItem);
          // 只保留最近100条记录
          if (existingCollections.length > 100) {
            existingCollections.splice(100);
          }
          localStorage.setItem(collectionKey, JSON.stringify(existingCollections));
          console.log('收藏已保存到本地存储');
        } else {
          console.log('该帖子已收藏，跳过重复添加');
        }
        post.value.isCollected = true;
        post.value.collectCount = (post.value.collectCount || 0) + 1;
        ElMessage.success('收藏成功（已保存到本地）');
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    ElMessage.error('操作失败');
  } finally {
    collectLoading.value = false;
  }
};

// 分享功能
const sharePost = () => {
  if (navigator.share) {
    navigator.share({
      title: post.value?.title,
      text: post.value?.content.substring(0, 100),
      url: window.location.href
    });
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      ElMessage.success('链接已复制到剪贴板');
    });
  }
};

// 评论功能
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }
  
  replyLoading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const newComment = {
      id: Date.now(),
      content: replyContent.value,
      user: {
        id: 999,
        username: '当前用户',
        avatarUrl: ''
      },
      likeCount: 0,
      createdAt: new Date().toISOString(),
      replies: []
    };
    
    comments.value.unshift(newComment);
    totalComments.value = comments.value.length;
    post.value.replyCount = (post.value.replyCount || 0) + 1;
    
    replyContent.value = '';
    showReplyForm.value = false;
    ElMessage.success('评论发表成功');
  } catch (error) {
    ElMessage.error('发表评论失败');
  } finally {
    replyLoading.value = false;
  }
};

const cancelReply = () => {
  replyContent.value = '';
  showReplyForm.value = false;
};

// 评论点赞
const toggleCommentLike = (comment: any) => {
  comment.likeCount = (comment.likeCount || 0) + 1;
  ElMessage.success('点赞成功');
};

// 回复评论
const replyToComment = (_comment: any) => {
  ElMessage.info('回复功能开发中...');
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

// 跳转到其他文章
const navigateToPost = (postId: number) => {
  router.push(`/forum/post/${postId}`);
};

// 页面加载时获取数据
onMounted(() => {
  loadPost();
});
</script>

<style lang="scss" scoped>
.post-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.dark-mode .post-detail-container {
  background-color: #1a1a1a;
}

.loading-container {
  padding: 40px;
}

.post-content {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.dark-mode .post-content {
  background-color: #2a2a2a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.post-header {
  padding: 30px;
  border-bottom: 1px solid #f0f0f0;
}

.dark-mode .post-header {
  border-bottom-color: #404040;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.author-avatar {
  flex-shrink: 0;
}

.author-details {
  .author-name {
    margin: 0 0 5px 0;
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
  }
  
  .post-time {
    margin: 0;
    font-size: 14px;
    color: #64748b;
  }
}

.dark-mode .author-details {
  .author-name {
    color: #ffffff;
  }
  
  .post-time {
    color: #b0b0b0;
  }
}

.post-actions {
  display: flex;
  gap: 10px;
}

.post-title {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 20px 0;
  line-height: 1.4;
}

.dark-mode .post-title {
  color: #ffffff;
}

.post-tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.post-tag {
  margin: 0;
}

.post-stats {
  display: flex;
  gap: 30px;
  padding: 20px 30px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #f0f0f0;
}

.dark-mode .post-stats {
  background-color: #333333;
  border-bottom-color: #404040;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #64748b;
  
  .el-icon {
    font-size: 16px;
  }
}

.dark-mode .stat-item {
  color: #b0b0b0;
}

.post-body {
  padding: 30px;
}

.post-content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #374151;
  
  :deep(h2) {
    font-size: 24px;
    font-weight: 600;
    color: #1e293b;
    margin: 30px 0 15px 0;
  }
  
  :deep(h3) {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 25px 0 10px 0;
  }
  
  :deep(p) {
    margin: 15px 0;
  }
  
  :deep(ul) {
    margin: 15px 0;
    padding-left: 20px;
  }
  
  :deep(li) {
    margin: 8px 0;
  }
}

.dark-mode .post-content-text {
  color: #e5e7eb;
  
  :deep(h2), :deep(h3) {
    color: #ffffff;
  }
}

.post-footer {
  padding: 20px 30px;
  border-top: 1px solid #f0f0f0;
  background-color: #f8f9fa;
}

.dark-mode .post-footer {
  border-top-color: #404040;
  background-color: #333333;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.comments-section {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 20px;
}

.dark-mode .comments-section {
  background-color: #2a2a2a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    margin: 0;
    color: #1e293b;
  }
}

.dark-mode .comments-header h3 {
  color: #ffffff;
}

.reply-form {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.dark-mode .reply-form {
  background-color: #333333;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.comments-list {
  margin-bottom: 30px;
}

.comment-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.dark-mode .comment-item {
  border-bottom-color: #404040;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
}

.comment-meta {
  flex: 1;
  
  .comment-author {
    font-weight: 600;
    color: #1e293b;
    margin-right: 10px;
  }
  
  .comment-time {
    font-size: 12px;
    color: #64748b;
  }
}

.dark-mode .comment-meta {
  .comment-author {
    color: #ffffff;
  }
  
  .comment-time {
    color: #b0b0b0;
  }
}

.comment-actions {
  display: flex;
  gap: 10px;
}

.comment-content {
  color: #374151;
  line-height: 1.6;
  margin-left: 44px;
}

.dark-mode .comment-content {
  color: #e5e7eb;
}

.comment-replies {
  margin-top: 15px;
  margin-left: 44px;
}

.reply-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.reply-content {
  flex: 1;
  
  .reply-author {
    font-weight: 600;
    color: #3b82f6;
    margin-right: 8px;
  }
  
  .reply-text {
    color: #374151;
    margin-right: 8px;
  }
  
  .reply-time {
    font-size: 12px;
    color: #64748b;
  }
}

.dark-mode .reply-content {
  .reply-text {
    color: #e5e7eb;
  }
  
  .reply-time {
    color: #b0b0b0;
  }
}

.comments-pagination {
  display: flex;
  justify-content: center;
}

.related-posts {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.dark-mode .related-posts {
  background-color: #2a2a2a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.related-posts h3 {
  margin: 0 0 20px 0;
  color: #1e293b;
}

.dark-mode .related-posts h3 {
  color: #ffffff;
}

.related-posts-list {
  display: grid;
  gap: 15px;
}

.related-post-item {
  padding: 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #3b82f6;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
  }
  
  h4 {
    margin: 0 0 8px 0;
    font-size: 16px;
    color: #1e293b;
  }
  
  p {
    margin: 0 0 10px 0;
    font-size: 14px;
    color: #64748b;
    line-height: 1.5;
  }
}

.dark-mode .related-post-item {
  border-color: #404040;
  
  &:hover {
    border-color: #66b1ff;
    box-shadow: 0 2px 8px rgba(102, 177, 255, 0.2);
  }
  
  h4 {
    color: #ffffff;
  }
  
  p {
    color: #b0b0b0;
  }
}

.related-post-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.dark-mode .related-post-meta {
  color: #808080;
}

@media (max-width: 768px) {
  .post-detail-container {
    padding: 10px;
  }
  
  .post-header {
    padding: 20px;
  }
  
  .post-title {
    font-size: 24px;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .post-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .post-stats {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .comment-content {
    margin-left: 0;
  }
  
  .comment-replies {
    margin-left: 0;
  }
}
</style>
